<template>
  <div class="w-full h-full text-white flex items-center justify-center relative px-20 box-border">
    <!-- 视频帧显示区域 -->
    <div class="w-full overflow-hidden relative h-[160px] scale-[2.1] left-[52.5%]">
      <img
        v-if="imgUrl"
        :src="imgUrl"
        class="w-full h-full"
        style="clip-path: inset(0 50% 0 0)"
        alt="视频帧"
      />
      <img
        v-else
        :src="TestImg"
        class="w-full h-full"
        style="clip-path: inset(0 50% 0 0)"
        alt="默认图片"
      />
    </div>

    <!-- 组件区域 -->
    <Box />

    <!-- 视频流组件 -->
    <Stream
      v-for="stream in streams"
      :key="stream.id"
      v-model="streamVisibles[stream.id]"
      :position="stream.position"
      :title="stream.title"
      :streamUrl="streamUrls[stream.id] || ''"
    />
  </div>
</template>

<script setup>
import { useWebSocket } from '@vueuse/core'
import TestImg from '@/assets/imgs/bottom1.jpg'
import Box from '@/components/Box1.vue'
import Stream from '@/components/Stream.vue'
import { nanoid } from 'nanoid'
import { getStreamUrl } from '@/api/api'
import { ref, watchEffect, onMounted, onUnmounted } from 'vue'

// 视频流配置数据 - 11个Stream
const streamConfigs = [
  { id: nanoid(), title: '监控点1', position: { left: '100px', top: '320px' }, camId: '1' },
  { id: nanoid(), title: '监控点2', position: { left: '360px', top: '320px' }, camId: '2' },
  { id: nanoid(), title: '监控点3', position: { left: '580px', top: '320px' }, camId: '3' },
  { id: nanoid(), title: '监控点4', position: { left: '800px', top: '320px' }, camId: '4' },
  { id: nanoid(), title: '监控点5', position: { left: '1000px', top: '320px' }, camId: '5' },
  { id: nanoid(), title: '监控点6', position: { left: '1200px', top: '320px' }, camId: '6' },
  { id: nanoid(), title: '监控点7', position: { left: '1560px', top: '320px' }, camId: '7' },
  { id: nanoid(), title: '监控点8', position: { left: '1800px', top: '320px' }, camId: '8' },
  { id: nanoid(), title: '监控点9', position: { left: '1960px', top: '320px' }, camId: '9' },
  { id: nanoid(), title: '监控点10', position: { left: '2200px', top: '320px' }, camId: '10' },
  { id: nanoid(), title: '监控点11', position: { left: '2450px', top: '320px' }, camId: '11' },
]

// 视频流状态管理
const streams = ref(
  streamConfigs.map((config) => ({
    ...config,
    visible: ref(false),
    url: ref(''),
  })),
)

// 创建响应式的URL映射
const streamUrls = ref({})
const streamVisibles = ref({})

// 初始化所有流的可见性状态
const initializeStreamStates = () => {
  streamConfigs.forEach((config) => {
    if (!streamVisibles.value.hasOwnProperty(config.id)) {
      streamVisibles.value[config.id] = false
    }
  })
}

// WebSocket连接
const { status, data, close } = useWebSocket(import.meta.env.VITE_BASE_WEBSOCKET1, {
  onConnected: (ws) => {
    console.log('WebSocket连接成功！', ws)
  },
  onDisconnected: (ws, event) => {
    console.log('WebSocket连接断开', event)
  },
  onError: (ws, event) => {
    console.error('WebSocket连接错误', event)
  },
  heartbeat: false,
  autoReconnect: true,
})

// 视频帧状态
const imgUrl = ref('')
let prevUrl = null

// 获取视频流URL的函数
const fetchStreamUrls = async () => {
  try {
    // 并行请求所有摄像头的streamUrl
    const promises = streamConfigs.map((config) => getStreamUrl({ cam_id: config.camId }))

    const responses = await Promise.all(promises)

    // 更新每个流的URL
    responses.forEach((response, index) => {
      if (response?.data?.length > 0) {
        const visibleStreamUrl = response.data[0].visible_stream_url
        if (visibleStreamUrl) {
          streamUrls.value[streamConfigs[index].id] = visibleStreamUrl
        }
      }
    })

    console.log('所有视频流URL获取完成:', Object.values(streamUrls.value))
  } catch (error) {
    console.error('获取视频流URL失败:', error)
  }
}

// 监听WebSocket数据变化
watchEffect(() => {
  if (data.value) {
    // 释放旧的 Blob URL，避免内存泄漏
    if (prevUrl) {
      URL.revokeObjectURL(prevUrl)
    }
    // 创建新的 Blob URL
    const newUrl = URL.createObjectURL(data.value)
    imgUrl.value = newUrl
    prevUrl = newUrl
  }

  if (status.value === 'CLOSED') {
    console.log('WebSocket连接已关闭，等待自动重连...')
  }
})

// 组件挂载时获取视频流URL
onMounted(() => {
  initializeStreamStates()
  fetchStreamUrls()
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 关闭WebSocket连接
  close()

  // 清理Blob URL，避免内存泄漏
  if (prevUrl) {
    URL.revokeObjectURL(prevUrl)
  }
})
</script>

<style lang="scss" scoped></style>
